package com.test.mybatis.generator;

import com.alibaba.fastjson.JSON;

import java.io.*;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.util.*;

/**
 * @author HelSing
 * @date 2019/3/18
 */
public class MessageCommentGenerator {

    private static List<String> c = new ArrayList<>();

    private static String path = "/Users/mac/dome";

    static {
        //哪个个表
        c.add("inbound_settlement");

    }

    public static void main(String[] args) throws Exception {
        FileInputStream inputStream = new FileInputStream(path + "/yf-granary/yf-granary-dao/src/test/java/com/test/mybatis/generator/msg/dome.md");
        String str = readFile(inputStream);
        //行分割标记
        String[] msgs = str.split("#");
        Map<String, String> map = new HashMap<>();
        for (String m : msgs) {
            //列分割标记
            String[] data = m.split("\\|");
            map.put(data[0], data[1].toLowerCase(Locale.ROOT));
        }

        System.out.println(JSON.toJSONString(map));
        msgCode(map);
    }

    private static void msgCode(Map<String, String> map) throws Exception {
        List<String> cz = new ArrayList<>();
        String url = "jdbc:mysql://rm-8vb43b03vawbw24k0oo.mysql.zhangbei.rds.aliyuncs.com:3306/yfgranary?serverTimezone=GMT";
        String user = "root";
        String password = "Jiajiale5";
        Class.forName("com.mysql.jdbc.Driver");
        Connection connection = DriverManager.getConnection(url, user, password);
        DatabaseMetaData metaData = connection.getMetaData();

        //获取数据库下面所有表
        ResultSet tables = metaData.getTables("yfgranary", null, "%", new String[]{"TABLE"});

        while (tables.next()) {
            // 列的个数
            int columnCount = tables.getMetaData().getColumnCount();
            // 根据指定列名称获取数据
            String TABLE_NAME = tables.getString("TABLE_NAME");
            String TABLE_SCHEM = tables.getString("TABLE_SCHEM");
            if (cz.contains(TABLE_NAME)) {
                continue;
            }
            if (!c.isEmpty()) {
                if (!c.contains(TABLE_NAME)) {
                    continue;
                }
            }
            System.out.println(TABLE_NAME);
            cz.add(TABLE_NAME);
            String head = convertName(TABLE_NAME);
            System.out.println(head);
            String h = head.substring(0, 1);
            FileInputStream inputStream = new FileInputStream(path + "/yf-granary/yf-granary-dao/src/test/java/com/test/mybatis/generator/model/msg.text");
            String str = readFile(inputStream);
            str = str.replace("${Table}", h.toUpperCase(Locale.ROOT) + head.substring(1));
//获取表的所有列
            ResultSet columns = metaData.getColumns("yfgranary", "%", TABLE_NAME, "%");
            StringBuilder property = new StringBuilder();

            while (columns.next()) {

                String COLUMN_NAME = columns.getString("COLUMN_NAME");
                String COLUMN_NAME_UP = convertName(COLUMN_NAME);
                String TYPE_NAME = columns.getString("TYPE_NAME");
                String REMARKS = columns.getString("REMARKS");
                if (COLUMN_NAME_UP.equals("created") || COLUMN_NAME_UP.equals("createUserId") ||
                        COLUMN_NAME_UP.equals("createUserName") || COLUMN_NAME_UP.equals("modified") ||
                        COLUMN_NAME_UP.equals("modificationUserId") || COLUMN_NAME_UP.equals("modificationUserName")
                        || COLUMN_NAME_UP.equals("yn")
                ) {
                    continue;
                }
                String types = "String ";
                if (TYPE_NAME.toLowerCase(Locale.ROOT).equals("bigint")) {
                    types = "Long ";
                } else if (TYPE_NAME.toLowerCase(Locale.ROOT).equals("tinyint") || TYPE_NAME.toLowerCase(Locale.ROOT).equals("int")) {
                    types = "Integer ";
                } else if (TYPE_NAME.toLowerCase(Locale.ROOT).equals("datetime")) {
                    types = "Date ";
                } else if (TYPE_NAME.toLowerCase(Locale.ROOT).equals("decimal")) {
                    types = "BigDecimal ";
                }
                Iterator<Map.Entry<String, String>> iterator = map.entrySet().iterator();
                String jf = "@JSONField(serialize = false)";
                if (REMARKS != null && !"".equals(REMARKS)) {

                    while (iterator.hasNext()){
                        Map.Entry<String, String> next = iterator.next();
                        if (REMARKS.contains(next.getKey())) {
                            String format = "";
                            if (next.getKey().endsWith("日期")) {
                                format = ", format=\"yyyy-MM-dd\"";
                            } else if(next.getKey().endsWith("时间")) {
                                format = ", format=\"yyyy-MM-dd HH:mm:ss\"";
                            }
                            jf = "@JSONField(name = \"" + next.getValue() + "\" " + format +")";
                            break;
                        }
                    }
                }
                property.append("/** ").append(REMARKS).append("**/").append(jf).append("private ").append(types).append(COLUMN_NAME_UP).append(";");
            }
            str = str.replace("${property}", property.substring(0, property.length() - 1) + ";");
            System.out.println(str);
            writeFile(str, h.toUpperCase(Locale.ROOT) + head.substring(1) + "RequestData.java");
        }

    }


    private static void writeFile(String str, String fileName) {
        String filePath = path + "/yf-granary/yf-granary-dao/src/test/java/com/test/mybatis/generator/file/";
        FileWriter fw = null;
        try {

            File file = new File(filePath);
            if (!file.exists()) {
                file.mkdirs();
            }
            File file2 = new File(filePath + fileName);

            if (!file2.exists()) {
                file.createNewFile();
            }
            fw = new FileWriter(filePath + fileName);
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(str);
            bw.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                fw.close();
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }

    private static String readFile(FileInputStream inputStream) throws IOException {

        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

        StringBuilder returnStr = new StringBuilder();

        String str = null;
        while ((str = bufferedReader.readLine()) != null) {
            returnStr.append(str);
        }
        inputStream.close();
        bufferedReader.close();

        return returnStr.toString();
    }

    private static String convertName(String columnName) {
        StringBuilder sb = new StringBuilder();
        String[] str = columnName.split("_");
        sb.append(str[0]);
        for (int i = 1, l = str.length; i < l; i++) {
            String s = str[i];
            sb.append(s.substring(0, 1).toUpperCase(Locale.ROOT));
            sb.append(s.substring(1));
        }
        return sb.toString();
    }
}


